import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { CaptchaEntity } from './captcha.entity';
import * as dayjs from 'dayjs';
type captcha = {
  key: string;
  captcha: string;
  validTime?: string;
};

@Injectable()
export class CaptchaService {
  constructor(
    @InjectRepository(CaptchaEntity)
    private readonly captchaRepository: Repository<CaptchaEntity>,
  ) {}

  //保存验证码
  async saveCaptcha(param: captcha) {
    await this.captchaRepository.save(param);
  }

  //验证验证码
  async validateCaptcha({ key, captcha }: captcha) {
    const data = await this.captchaRepository.findOne({ where: { key } });
    if (!data) {
      throw new HttpException(
        {
          message: '请先获取验证码',
          error: '请先获取验证码',
        },
        HttpStatus.BAD_REQUEST,
      );
    } else if (data.captcha !== captcha) {
      throw new HttpException(
        {
          message: '验证码不正确',
          error: '验证码不正确',
        },
        HttpStatus.BAD_REQUEST,
      );
    }
    if (dayjs(data?.validTime).valueOf() < dayjs().valueOf()) {
      throw new HttpException(
        {
          message: '验证码已过期',
          error: '验证码已过期',
        },
        HttpStatus.BAD_REQUEST,
      );
    }
    return true;
  }
}
